package com.ssly.media.manage.ffmpeg;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Media {
    private final static String BITRATE_REGEX = "bitrate:([^(,+})]*)kb/s";
    private final static String HEIGHT_REGEX = "Video:[\\s\\S]*,\\s\\d*x(\\d*)";
    private final static String WIDTH_REGEX = "Video:[\\s\\S]*,\\s(\\d*)x\\d*";
    private final static String DURATION_REGEX = "Duration:([^(,+})]*),";
    private final static String FPS_REGEX = "Video:[\\s\\S]*,\\s([^(,+})]*)fps";
    private final static String VCODEC_REGEX = "Video:([^(,+})]*)";
    private final static String ACODEC_REGEX = "Audio:([^(,+})]*)";


    private String filePath;

    private Integer bitrate;
    private String duration;
    private Integer lenght;
    private Integer height;
    private Integer width;
    private Float fps;
    private String fileDir;
    private String fileName;
    private String vcodec;
    private String acodec;
    private String stdInfo;

    public static void main(String[] args) {
        File file = new File("E:\\XMPCache\\星球大战8：最后的绝地武士BD中英双字[飘花www.piaohua.com].mp4");
        new Media(file);
    }

    public Media(File file) {
        this.filePath = file.getAbsolutePath();
        this.fileDir = file.getParent();
        this.fileName = file.getName();
        if (!file.exists()) {
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            return;
        }
        List<String> command = new ArrayList<>();
        command.add("ffmpeg");
        command.add("-i");
        command.add(filePath);

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.redirectErrorStream(true);
        try {
            Process process = processBuilder.start();
            InputStream inputStream = process.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains("Duration") || line.contains("Stream"))
                    stringBuilder.append(line).append("\n");
            }
            this.stdInfo = stringBuilder.toString();
            int exitVal = process.waitFor();
            System.out.println("Process exitValue: " + exitVal);
            System.out.print(stdInfo);

            dumpMetaData();

            System.out.println(this.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Media(String filePath) {
        this(new File(filePath));
    }

    public Media(String fileDir, String fileName) {
        this(fileDir + File.separator + fileName);
    }

    public Integer getBitrate() {
        return bitrate;
    }

    public void setBitrate(Integer bitrate) {
        this.bitrate = bitrate;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public Integer getLenght() {
        return lenght;
    }

    public void setLenght(Integer lenght) {
        this.lenght = lenght;
    }

    public Integer getHeight() {
        return height;
    }

    public void setHeight(Integer height) {
        this.height = height;
    }

    public Integer getWidth() {
        return width;
    }

    public void setWidth(Integer width) {
        this.width = width;
    }

    public String getFileDir() {
        return fileDir;
    }

    public void setFileDir(String fileDir) {
        this.fileDir = fileDir;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getVcodec() {
        return vcodec;
    }

    public void setVcodec(String vcodec) {
        this.vcodec = vcodec;
    }

    public String getAcodec() {
        return acodec;
    }

    public void setAcodec(String acodec) {
        this.acodec = acodec;
    }

    public String getStdInfo() {
        return stdInfo;
    }

    public void setStdInfo(String stdInfo) {
        this.stdInfo = stdInfo;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public Float getFps() {
        return fps;
    }

    public void setFps(Float fps) {
        this.fps = fps;
    }

    @Override
    public String toString() {
        return "Media{" +
                "bitrate=" + bitrate +
                ", duration='" + duration + '\'' +
                ", lenght=" + lenght +
                ", height=" + height +
                ", width=" + width +
                ", fps=" + fps +
                ", fileDir='" + fileDir + '\'' +
                ", fileName='" + fileName + '\'' +
                ", vcodec='" + vcodec + '\'' +
                ", acodec='" + acodec + '\'' +
                '}';
    }

    private void dumpMetaData() {
        this.bitrate = Integer.valueOf(extract(BITRATE_REGEX));
        this.width = Integer.valueOf(extract(WIDTH_REGEX));
        this.height = Integer.valueOf(extract(HEIGHT_REGEX));
        this.duration = extract(DURATION_REGEX);
        this.acodec = extract(ACODEC_REGEX);
        this.vcodec = extract(VCODEC_REGEX);
        this.fps = Float.valueOf(extract(FPS_REGEX));

        String[] split = duration.split(":");
        this.lenght = (int) (Integer.valueOf(split[0]) * 60 * 60 + Integer.valueOf(split[1]) * 60 + Double.valueOf(split[2]));
    }

    //提取信息
    private String extract(String regex) {
        String str = "";
        Pattern pattern = Pattern.compile(regex);
        //2.将字符串和正则表达式相关联
        Matcher matcher = pattern.matcher(this.stdInfo);
        //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。

        //查找符合规则的子串
        while (matcher.find()) {
            //获取 字符串
            str = matcher.group(1).trim();
        }
        return str;
    }

    public static Integer getLenght(String time) {
        String[] split = time.split(":");
        return (int) (Integer.valueOf(split[0]) * 60 * 60 + Integer.valueOf(split[1]) * 60 + Double.valueOf(split[2]));
    }

}
